package sc.server;

import java.io.FileReader;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.LogManager;
import java.util.logging.Logger;

import sc.nio.NioServer;
import sc.server.world.Tile;

public final class Server
{
	// Server properties file
	private static final String PROPERTIES_FILE = "server.properties";

	// The Logger instance accessible to all
	public static Logger logger = null;
	// Scale of coordinates i.e. A Container with x = 100, is OpenGL x-axis = 1
	public static int SCALE = 100;

	// Visibility of data i.e. something happens everything within n tiles hears
	// about it
	public static int VISIBILITY = 100;

	// Non-blocking client communicator
	public static NioServer nio;

	/**
	 * Creates an instance of MMOServer.
	 */
	public Server()
	{

	}

	/**
	 * Program entry method.
	 */
	public static void main(String[] args)
	{
		Properties properties;
		FileReader reader;
		ClientHandler inputhandler;
		int port;

		try
		{
			// Configure java.util.logging and get a Logger instance
			System
					.setProperty("java.util.logging.config.file",
							PROPERTIES_FILE);
			LogManager logManager = LogManager.getLogManager();
			logManager.readConfiguration();
			logger = Logger.getLogger("");

			// Read the properties configuration
			reader = new FileReader(PROPERTIES_FILE);
			properties = new Properties();
			properties.load(reader);

			// Get port configuration
			port = Integer.parseInt(properties.getProperty("sc.server.port"));

			Server.logger.info(properties.getProperty("sc.server.version"));

			// Preload map tiles
			if (Tile.get(0, 0) == null)
				return;

			// Create an InputHandler instance and start its thread
			inputhandler = new ClientHandler();
			Thread t = new Thread(inputhandler);
			t.start();

			// Create an NioServer instance and start its thread
			nio = new NioServer(null, port, inputhandler);
			nio.setLogIO(true);
			t = new Thread(nio);
			t.start();

			Server.logger.info("Listening on port "
					+ properties.getProperty("sc.server.port") + "...");
		}
		catch (Exception e)
		{
			logger.severe(e.getMessage());
		}
		finally
		{
			try
			{
				Database.close();
			}
			catch (SQLException e)
			{
				logger.severe(e.getMessage());
			}
		}
	}
}
